package com.vaoi.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.vaoi.modelo.Roles;
import com.vaoi.modelo.control.IRolesLogic;
import com.vaoi.modelo.control.IUsuariosLogic;
import com.vaoi.modelo.dto.UsuariosDTO;

@Component("VortexAuthenticationProvider")
public class VortexAuthenticationProvider implements AuthenticationProvider {
	
	@Autowired
	private IUsuariosLogic usuariosLogic;
	@Autowired
    private IRolesLogic rolesLogic;
	
	    @Override
	    public Authentication authenticate(Authentication authentication)throws AuthenticationException {
	         
	        String name = authentication.getName();
	        String password = authentication.getCredentials().toString();
	        
			try {
				List<UsuariosDTO> usuariosDTOs = usuariosLogic.getDataUsuarios();
				
				if(usuariosDTOs!=null){
			        for (int i = 0; i < usuariosDTOs.size(); i++) {
			        	
			            if (name.equalsIgnoreCase(usuariosDTOs.get(i).getEmail()) && password.equals(usuariosDTOs.get(i).getClave()) && usuariosDTOs.get(i).getEstadoRegistro().equals("A")) {
			            	Roles Rol= rolesLogic.getRoles(usuariosDTOs.get(i).getCodigoRol_Roles());
			                final List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
			                grantedAuths.add(new SimpleGrantedAuthority(Rol.getNombreRol()));
			                final UserDetails principal = new User(usuariosDTOs.get(i).getNombre(), password, grantedAuths);
			                final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
			                return auth;
			            }
			            
					}
				}
				
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			
	        return null;
	    }
	 
	    /**
	     * Este metodo se llama primero cuando se autentica un usuario
	     */
	    @Override
	    public boolean supports(Class<?> authentication) {
	         return authentication.equals(UsernamePasswordAuthenticationToken.class);
	    }

}